<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- type 显示颜色 success center 居中显示  -->
      <el-alert title="添加商品信息" type="info" center show-icon>
      </el-alert>
      <!-- active 默认0 1代表第一个 align-center 居中 finish-status
        完成之后的状态,字体颜色 space 数字之间的间隔 -->
      <!-- <el-steps :space="200" :active="Number.parseInt(active)" align-center finish-status="success"> -->
      <el-steps :space="200" :active="active - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form label-position="top" label-width="80px" :rules="addGoodFormRule" :model="addGoodForm">
        <el-tabs :before-leave="beforeLeave" v-model="active" tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(kg)" prop="goods_weight">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader @change="cascaderChg" v-model="addGoodForm.goods_cat" :options="options"
                :props="props"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框 -->
            <el-form-item :label="t1.attr_name" v-for="t1 in attrMany" :key="t1.attr_id">
              <el-checkbox-group v-model="t1.attr_vals">
                <el-checkbox border :label="t2" v-for="(t2, index) in t1.attr_vals" :key="index"> </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 多个输入框 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in attrOnly" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传的ip地址不经过request的,所以需要自己写好路径list-type文件列表的类型text/picture/picture-card
            headers设置请求头 -->
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload" list-type="picture-card"
              :headers="headers" :on-success="onSuccessImg" :on-preview="onPreviewImg" :on-remove="onRemoveImg">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor class='editor' v-model="addGoodForm.goods_introduce" ref="myQuillEditor">
            </quill-editor>
            <el-button class="submit" type="primary" @click="AddGood">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示图片dialog -->
    <el-dialog title="图片预览" :visible.sync="dialogVisibleImg" width="50%">
      <img style="width: 100%;" :src="previewImgUrl" alt="" srcset="">
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      active: "0",
      // 保存表单信息
      addGoodForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: '',
        // 商品分类
        goods_cat: [],
        pics: []
      },
      // 校验信息,属性名字必须一样
      addGoodFormRule: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      options: [],
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 分类的属性,动态参数
      attrMany: [],
      // 商品属性,静态参数
      attrOnly: [],
      // 图片的请求头
      headers: {},
      // 图片预览
      dialogVisibleImg: false,
      previewImgUrl: ''
    }
  },
  mounted () {
    this.getCategoriesArr()
  },
  methods: {
    // 获取分类数组
    async getCategoriesArr () {
      const { data: { data, meta } } = await request({
        url: "/categories",
        method: "GET"
      })
      if (meta.status !== 200) {
        return this.$message.error('获取分类失败')
      }
      this.options = data
      // console.log(data);
    },
    // 级联选择器改变的时候触发
    cascaderChg () {
      if (this.addGoodForm.goods_cat.length !== 3) {
        this.addGoodForm.goods_cat = []
      }
      console.log("改变了");
    },
    // tabclick点击的时候触发
    beforeLeave (activeName, oldActiveName) {
      // console.log(activeName, oldActiveName);
      // 3可以放行, "0"
      if (!(activeName === "0" || this.addGoodForm.goods_cat.length === 3)) {
        this.$message.error("请选择商品分类")
        // 给出提示
        return false
      }
      // 获取分类的参数
      if (activeName === "1") {
        this.getCategoriesAttr()
      }
      // 获取商品属性
      if (activeName === "2") {
        this.getCategoriesAttrOnly()
      }
      // 上传图片
      if (activeName === "3") {
        this.headers.Authorization = sessionStorage.getItem("token")
      }
    },
    // 获取商品参数
    async getCategoriesAttr () {
      const { data: { data, meta } } = await request({
        url: `/categories/${this.addGoodForm.goods_cat[2]}/attributes`,
        params: {
          sel: 'many'
        },
        method: "GET"
      })
      if (meta.status !== 200) {
        return this.$message.error("获取分类参数错误")
      }
      // data是数组
      // console.log(data);
      data.forEach(obj => {
        obj.attr_vals = obj.attr_vals.split(" ")
        // 新田的数据,手动勾选
        obj.attr_arr = []
      });
      this.attrMany = data
    },
    // 静态的参数
    async getCategoriesAttrOnly () {
      const { data: { data, meta } } = await request({
        url: `/categories/${this.addGoodForm.goods_cat[2]}/attributes`,
        params: {
          sel: 'only'
        },
        method: "GET"
      })
      if (meta.status !== 200) {
        return this.$message.error("商品属性获取错误")
      }
      console.log(data);
      this.attrOnly = data
    },
    onSuccessImg (response, file, fileList) {
      // console.log(response);
      // console.log(file);
      const obj = { pic: response.data.tmp_path, uid: file.uid }
      this.addGoodForm.pics.push(obj)
    },
    onPreviewImg (file) {
      // 对话框显示
      this.dialogVisibleImg = true
      // 图片赋值
      this.previewImgUrl = file.response.data.url
    },
    onRemoveImg (file, fileList) {
      // console.log(file);
      // console.log(fileList);
      // 通过uid 找下标
      const i = this.addGoodForm.pics.findIndex((item) => {
        return item.uid === file.uid
      })
      // console.log(i);
      this.addGoodForm.pics.splice(i, 1)
    },
    // 添加商品
    async AddGood () {
      // 添加商品参数
      this.addGoodForm.attrs = []
      this.attrMany.forEach((obj) => {
        const attr_id = obj.attr_id;
        const attr_value = obj.attr_vals.join(" ");
        this.addGoodForm.attrs.push({ attr_id, attr_value })
      })
      // 商品参数
      this.attrOnly.forEach((obj) => {
        const attr_id = obj.attr_id;
        const attr_value = obj.attr_vals
        this.addGoodForm.attrs.push({ attr_id, attr_value })
      })
      // 商品属性
      this.addGoodForm.goods_cat = this.addGoodForm.goods_cat.join(",")
      // 提交数据
      const { data: { meta } } = await request({
        url: "/goods",
        method: "POST",
        data: this.addGoodForm
      })
      if (meta.status !== 201) {
        return this.$message.error("添加失败")
      }
      // 跳转商品列表
      // this.$router.push("/home/goods")
      this.$router.push({ name: "goods" })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tabs {
  margin-top: 20px;
}

.editor {
  height: 400px;
}

.submit {
  margin-top: 20px;
}
</style>
